package com.zifan.sever.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.zifan.sever.bean.Admin;
import com.zifan.sever.bean.Menu;
import com.zifan.sever.mapper.MenuMapper;
import com.zifan.sever.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zifan
 * @since 2021-04-10
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Menu> getMenusByAdminId() {
        //先在spring security的全局上下文中获取当前对象信息。
        Admin admin = (Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer id = admin.getId();

//        List<Menu> menus = null;

        //redis相关
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        //从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("meun_" + id);
        if (CollUtil.isEmpty(menus)){
            //如果为空，就通过数据库去查询
            menus = baseMapper.getMenusByAdminId(id);
            //将此数据设置到redis中
            valueOperations.set("meun_" + id,menus);
        }

        return menus;
    }


    /**
     * 根据角色获取菜单列表
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return baseMapper.getMenusWithRole();
    }

    /**
     * 查询所有的菜单列表，每个菜单中带有属于自己的子菜单
     * @return
     */
    @Override
    public List<Menu> getMenusWithChildren() {
        return baseMapper.getMenusWithChildren();
    }

}
